import Taro, { Component, getUserInfo } from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'
import { AtTabs, AtTabsPane, AtActionSheet, AtInput } from 'taro-ui'
import { DNavBar, DCarInfo, DItemError, DModal, Ddialog } from '@/components'
import http from '@/api'
import common from '@/common'
import './usercar.scss'

export default class UsercarBox extends Component {

    constructor(props) {
        super(props)
        this.state = {
            accContent: "本企业尚未开通企业收款账户，不能进行次操作，是否开通企业收款账户？",
            imIdStatus: "",
            active: 0, // 0 上架中 1 已过期
            isOpened: false,
            value: '',
            oldVal: '',
            altValue: '',
            id: '',
            handle: '',
            currPage: 1,
            pageSize: 10,
            totalCount: 0,
            totalPage: 1,
            isShow: false,
            showAuthTip: false,
            showAccDialog: false,
            scrollHeight: window.screen.availHeight,
            handleOK: () => { },
            buttonList: [
                {
                    text: '改价',
                    onClick: this.firstHandle.bind(this)
                },
                {
                    text: '发布同款',
                    onClick: this.startCar
                },
                {
                    text: '下架',
                    onClick: this.stopCar
                }
            ],
            buttonList1: [
                {
                    text: '发布同款',
                    onClick: this.startCar
                },
                {
                    text: '删除',
                    onClick: this.delMySearchCar
                }
            ],
            list: [],
            firstList: [],
            secondlist: [],
            itemStatus: false
        }
    }

    componentWillMount = () => {
        let { active = 0 } = this.$router.params
        this.handleClick(+active)
        // this.httpCarSourceList()
    }

    componentDidShow() {
        this.setState({
            list: [],
            currPage: 1,
            totalPage: 1,
            itemStatus: false
        }, () => {
            this.httpCarSourceList()
        })
    }


    //修改tab
    handleClick(active) {
        this.setState({
            list: [],
            currPage: 1,
            active,
            totalPage: 1,
            itemStatus: false
        }, () => this.httpCarSourceList())
    }
    //改价
    firstHandle(item) {
        let { isOpened } = this.state
        isOpened = !isOpened
        this.setState({
            isOpened,
            id: item.id,
            altValue: +item.carOfferPrice,
            value: +item.carOfferPrice
        })
    }
    //详情
    handleDetail(item) {
        let { active } = this.state
        if (active === 1) {
            return Taro.showToast({
                title: '该车源已过期',
                icon: 'none'
            })
        }
        Taro.navigateTo({
            url: `/pages/carsourcedetails/carsourcedetails?id=${item.id}&status=${active}`
        })
    }
    //删除
    onDetailHandle(item) {
        let { isShow, handle } = this.state
        isShow = !isShow
        handle = '删除'
        this.setState({
            isShow,
            id: item.id,
            handle
        })
    }

    //关闭改价框/模态框
    onCancelHandle = () => {
        this.setState({
            isOpened: false,
            isShow: false
        })
    }
    //提交改价
    onSubmitHandle = () => {
        let { value, id, altValue } = this.state

        let indList = this.state.list.filter(list => id == list.id)
        let lPri = 0
        let nVal = this.state.oldVal
        if (!+value) {
            return Taro.showToast({
                icon: 'none',
                title: '请输入修改后报价价格！'
            })
        }
        if (+value === +altValue) {
            return Taro.showToast({
                icon: 'none',
                title: '尚未修改报价！'
            })
        }
        if (indList) {
            if (indList.length) {
                lPri = indList[0].carGuiPrice
            }
        }

        // 改价须在指导价的0.5-2倍之间
        if (value <= lPri * 2 && value >= lPri * 0.5) {
            nVal = value
        } else {

            Taro.showToast({
                title: "改价须在市场指导价的0.5-2倍之间",
                icon: 'none'
            })
            this.setState({
                value: nVal
            })
            return
        }

        // 调用后台接口修改报价
        http.setMySourceCarChangePrice({ id: id, carOfferPrice: value }).then(res => {
            if (res) {
                Taro.showToast({
                    icon: 'none',
                    title: '修改成功！'
                })
                this.setState({
                    isOpened: false,
                    currPage: 1,
                    list: [],
                    totalPage: 1
                }, this.httpCarSourceList)
            } else {
                Taro.showToast({
                    icon: 'none',
                    title: '修改失败！'
                })
            }
        })
    }

    // 发布同款
    startCar = (item) => {
        // sessionStorage.setItem('_startCar', JSON.stringify(item))
        this.onHandleForm(item.id)
    }

    //下架
    stopCar = item => {
        const cb = () => {
            this.setState({
                isShow: false,
                handle: ''
            })
            http.stopMySearchCarTakeOff({
                id: item.id
            }).then(res => {
                if (res) {
                    Taro.showToast({
                        title: '下架成功！',
                        duration: 800
                    }).then(() => {
                        setTimeout(() => {
                            this.setState({
                                currPage: 1,
                                list: [],
                                totalPage: 1
                            },
                                // this.httpCarSourceList
                                Taro.redirectTo({
                                    url: `/pages/usercar/usercar?active=1`
                                })
                            )
                        }, 1000)
                    })

                } else {
                    Taro.showToast({
                        icon: 'none',
                        title: '下架失败！'
                    })
                }
            })
        }
        this.setState({
            handle: '下架',
            isShow: true,
            handleOK: cb
        })
    }

    delMySearchCar = item => {
        const cb = () => {
            this.setState({
                isShow: false,
                handle: ''
            })
            http.delMySearchCar({ id: item.id }).then(res => {
                if (res) {
                    Taro.showToast({
                        title: '删除成功！',
                        duration: 800
                    }).then(res => {
                        setTimeout(() => {
                            this.setState({
                                currPage: 1,
                                list: [],
                                totalPage: 1
                            }, this.httpCarSourceList)
                        }, 1000)
                    })

                } else {
                    Taro.showToast({
                        icon: 'none',
                        title: '删除失败！'
                    })
                }
            })
        }
        this.setState({
            handle: '删除',
            isShow: true,
            handleOK: cb
        })
    }

    //绑定输入框
    handleChange(value) {

        let Digit = common.getDigit(value, this.state.value)

        this.setState({
            oldVal: this.state.value,
            value: Digit
        })
    }
    //发布车源
    async onHandleForm(id = '') {
        const { eaIsAppro } = await http.getConfirmInfo()
        const { imIdStatus } = await http.myselfDetail()
        const { accountStatus } = await http.myInfo()

        if (eaIsAppro != 1 && imIdStatus != 2) {
            // 企业没有认证并且不是企业员工
            this.setState({
                showAuthTip: true,
            })
        } else {
            // 企业认证或者是企业员工
            if (accountStatus != 1000) {
                // 没有开通电子账户
                if (imIdStatus == 2) {
                    this.setState({
                        imIdStatus,
                        accContent: '本企业尚未开通企业收款账户，请联系企业管理员开通后再操作。'
                    })
                }
                this.setState({
                    showAccDialog: true
                })
            } else {
                // 开通了电子账户
                Taro.navigateTo({
                    url: `/pages/carform/carform?status=${2}&id=${id}`
                })
            }

        }
    }
    //模态框确认按钮
    onDelHandle() {
        this.onCancelHandle()
        this.state.handleOK()
    }

    httpCarSourceList = (isAppend = false) => {
        const { pageSize, currPage, totalPage, active } = this.state
        if (currPage > totalPage) {
            this.setState({
                itemStatus: true
            })
            return
        }
        let _http
        if (!active) {
            _http = http.getCarSourceList({
                pageSize,
                page: currPage
            })
        } else {
            _http = http.getCarSourceListTakeOff({
                pageSize,
                page: currPage
            })
        }
        _http.then(res => {
            if (isAppend) {
                const { list } = this.state
                res.list = [...list, ...res.list]
            }
            this.setState({
                ...res,
                itemStatus: false,
                totalPage: res.totalPage
            })
        })
    }

    onScrollEnd = () => {
        this.setState({
            currPage: this.state.currPage + 1
        }, () => this.httpCarSourceList(true))
    }

    onCancel() {
        this.setState({
            showAccDialog: false,
            showAuthTip: false,
        })
    }
    onSure() {
        this.onCancel()
        Taro.navigateTo({
            url: `/pages/myinfo/authentication`
        })
    }
    onSure2() {
        this.onCancel()
        if (this.state.imIdStatus == 2) return
        Taro.navigateTo({
            url: `/pages/accountBook/accountBook`
        })
    }

    render() {
        const {
            active,
            isOpened,
            value,
            isShow,
            handle,
            scrollHeight,
            list,
            buttonList,
            buttonList1,
            itemStatus,
            showAuthTip,
            showAccDialog,
            imIdStatus,
            accContent
        } = this.state
        const tabList = [{ title: '上架中', value: 1 }, { title: '已过期', value: 0 }]
        return (
            <View className='b_usercar'>
                <DNavBar title={'我的车源'}></DNavBar>
                <View className='b_usercar__box'>
                    <View className='b_usercar__content'>
                        <AtTabs current={active} tabList={tabList} onClick={this.handleClick.bind(this)}>
                            {
                                tabList.map(tab => <AtTabsPane>
                                    <ScrollView
                                        className='b_usercar__content_item'
                                        scrollY
                                        scrollWithAnimation
                                        lowerThreshold='20'
                                        style={`height:${scrollHeight - 100}PX`}
                                        onScrollToLower={this.onScrollEnd}
                                    >
                                        {
                                            list && list.map((item, i) => {

                                                return <DCarInfo
                                                    key={i}
                                                    place={item.place}
                                                    money={item.carGuiPrice}
                                                    firstText={item.firstText}
                                                    nameList={[item.carDataModel]}
                                                    infoList={[item.carSourceType, item.carEmissionStd, '外观颜色:', item.carOutColor]}
                                                    carmoney={item.carOfferPrice}
                                                    icon={item.icon}
                                                    company={item.entName}
                                                    clock={item.ago}
                                                    item={item}
                                                    onDetail={this.handleDetail.bind(this, item)}
                                                    buttonList={active ? buttonList1 : buttonList}
                                                >
                                                </DCarInfo>
                                            })
                                        }
                                        {
                                            list.length > 0 && itemStatus && <View className='b_usercar__more'>暂无更多</View>
                                        }
                                    </ScrollView>
                                </AtTabsPane>)
                            }
                        </AtTabs>
                    </View>
                </View>

                {
                    list.length === 0 && <DItemError></DItemError>
                }


                <AtActionSheet isOpened={isOpened} onClose={this.onCancelHandle.bind(this)}>
                    <View className='b_usercar__money'>
                        <Text className='b_usercar__money_cancel' onClick={this.onCancelHandle.bind(this)}>取消</Text>
                        <Text className='b_usercar__money_title'>改价</Text>
                        <Text className='b_usercar__money_submit' onClick={this.onSubmitHandle.bind(this)}>提交</Text>
                    </View>
                    <View className='b_usercar__input'>
                        <AtInput value={value} onChange={this.handleChange.bind(this)} className='b_usercar__input_money' title='报价价格' type='number' placeholder='请输入修改后报价'></AtInput>
                        <View className='b_usercar__input_item'>万元</View>
                    </View>
                </AtActionSheet>

                <View className='b_usercar__createform' onClick={this.onHandleForm.bind(this, '')}>
                    <View className='b_usercar__createform_box'>
                        <View className='b_usercar__createform_font'>发起</View>
                        <View className='b_usercar__createform_font'>车源</View>
                    </View>
                </View>
                <View>
                    <DModal
                        isShow={isShow}
                        text={`您确认${handle}该车源信息？`}
                        onFirst={this.onCancelHandle.bind(this)}
                        onLast={this.onDelHandle.bind(this)}
                        onCancel={this.onCancelHandle.bind(this)}>
                    </DModal>
                </View>

                <Ddialog isShow={showAuthTip} content="为了您的交易安全，请进行信息认证 信息认证后可或得更多权限" btnText="前往认证" onCancel={this.onCancel.bind(this)} onSure={this.onSure.bind(this)}></Ddialog>
                <Ddialog isShow={showAccDialog} content={accContent} btnText={imIdStatus == 2 ? "我知道了" : "前往开通"} onCancel={this.onCancel.bind(this)} onSure={this.onSure2.bind(this)}></Ddialog>
            </View>
        )
    }
}
